package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// MemberController 处理会员相关请求
type MemberController struct {
	web.Controller
}

// List 获取会员列表
func (c *MemberController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 解析过滤条件
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 会员姓名
	if name := c.GetString("name"); name != "" {
		filters["name"] = name
	}

	// 会员手机号
	if phone := c.GetString("phone"); phone != "" {
		filters["phone"] = phone
	}

	// 会员等级
	if levelId, err := c.GetInt64("level_id", 0); err == nil && levelId > 0 {
		filters["level_id"] = levelId
	}

	// 会员状态
	if status, err := c.GetInt8("status", -1); err == nil && status != -1 {
		filters["status"] = status
	}

	// 性别筛选
	if gender, err := c.GetInt8("gender", -1); err == nil && gender != -1 {
		filters["gender"] = gender
	}

	// 注册时间范围
	if startTime, err := c.GetInt64("start_time", 0); err == nil && startTime > 0 {
		filters["start_time"] = startTime
	}

	if endTime, err := c.GetInt64("end_time", 0); err == nil && endTime > 0 {
		filters["end_time"] = endTime
	}

	// 余额范围
	if minBalance, err := c.GetFloat("min_balance", -1); err == nil && minBalance >= 0 {
		filters["min_balance"] = minBalance
	}

	if maxBalance, err := c.GetFloat("max_balance", -1); err == nil && maxBalance > 0 {
		filters["max_balance"] = maxBalance
	}

	// 积分范围
	if minPoints, err := c.GetInt("min_points", -1); err == nil && minPoints >= 0 {
		filters["min_points"] = minPoints
	}

	if maxPoints, err := c.GetInt("max_points", -1); err == nil && maxPoints > 0 {
		filters["max_points"] = maxPoints
	}

	// 累计消费金额范围
	if minConsume, err := c.GetFloat("min_consume", -1); err == nil && minConsume >= 0 {
		filters["min_consume"] = minConsume
	}

	if maxConsume, err := c.GetFloat("max_consume", -1); err == nil && maxConsume > 0 {
		filters["max_consume"] = maxConsume
	}

	// 获取会员列表
	members, total, err := models.GetMemberList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回会员列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取会员列表成功",
		"data": map[string]interface{}{
			"list":  members,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// GetOne 获取会员详情
func (c *MemberController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析会员ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员信息
	member, err := models.GetMemberById(id, permResult.Admin.FranchiseId)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && member.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问该会员信息",
		}
		c.ServeJSON()
		return
	}

	// 返回会员信息
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取会员信息成功",
		"data":    member,
	}
	c.ServeJSON()
}

// Create 创建会员
func (c *MemberController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var member models.Member
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &member)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 验证必填字段
	if member.Name == "" || member.Phone == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员姓名和手机号不能为空",
		}
		c.ServeJSON()
		return
	}

	// 检查手机号是否已存在
	existMember, _ := models.GetMemberByPhone(member.Phone, permResult.Admin.FranchiseId)
	if existMember != nil && existMember.Id > 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该手机号已被注册",
		}
		c.ServeJSON()
		return
	}

	// 设置默认值
	member.Status = 1
	member.RegisterIp = c.Ctx.Input.IP()

	// 设置加盟商ID
	member.FranchiseId = permResult.Admin.FranchiseId
	member.CreatedBy = permResult.Admin.Username
	member.UpdatedBy = permResult.Admin.Username

	// 创建会员
	id, err := models.CreateMember(&member)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建会员失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回创建结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建会员成功",
		"data":    id,
	}
	c.ServeJSON()
}

// Update 更新会员信息
func (c *MemberController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析会员ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员信息
	member, err := models.GetMemberById(id, permResult.Admin.FranchiseId)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && member.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改该会员信息",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var updateMember models.Member
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &updateMember)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 更新会员信息
	if updateMember.Name != "" {
		member.Name = updateMember.Name
	}
	if updateMember.Avatar != "" {
		member.Avatar = updateMember.Avatar
	}
	if updateMember.Gender != 0 {
		member.Gender = updateMember.Gender
	}
	if updateMember.Birthday != 0 {
		member.Birthday = updateMember.Birthday
	}
	if updateMember.LevelId != 0 {
		member.LevelId = updateMember.LevelId
	}
	if updateMember.Status != 0 {
		member.Status = updateMember.Status
	}

	// 更新修改信息
	member.UpdatedBy = permResult.Admin.Username
	member.UpdatedAt = time.Now().Unix()

	// 更新会员
	err = models.UpdateMember(member, permResult.Admin.FranchiseId, "Name", "Avatar", "Gender", "Birthday", "LevelId", "Status", "UpdatedAt", "UpdatedBy")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新会员失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回更新结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新会员成功",
		"data":    member,
	}
	c.ServeJSON()
}

// Delete 删除会员
func (c *MemberController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析会员ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员信息
	member, err := models.GetMemberById(id, permResult.Admin.FranchiseId)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && member.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权删除该会员",
		}
		c.ServeJSON()
		return
	}

	// 删除会员
	err = models.DeleteMember(id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除会员失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回删除结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除会员成功",
	}
	c.ServeJSON()
}

// UpdatePoints 更新会员积分
func (c *MemberController) UpdatePoints() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析会员ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员信息
	member, err := models.GetMemberById(id, permResult.Admin.FranchiseId)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && member.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改该会员积分",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	type UpdatePointsRequest struct {
		Points      int    `json:"points"`      // 变动积分，正数为增加，负数为减少
		Description string `json:"description"` // 变动描述
	}

	var req UpdatePointsRequest
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 验证积分
	if req.Points == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "变动积分不能为0",
		}
		c.ServeJSON()
		return
	}

	// 更新会员积分并记录
	err = models.AddMemberPoints(
		id,
		req.Points,
		2, // 2:管理员调整
		"",
		req.Description,
		permResult.Admin.Username,
		permResult.Admin.FranchiseId,
	)

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新会员积分失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回更新结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新会员积分成功",
	}
	c.ServeJSON()
}

// UpdateBalance 更新会员余额
func (c *MemberController) UpdateBalance() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析会员ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员信息
	member, err := models.GetMemberById(id, permResult.Admin.FranchiseId)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && member.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改该会员余额",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	type UpdateBalanceRequest struct {
		Amount      float64 `json:"amount"`      // 变动金额，正数为增加，负数为减少
		Description string  `json:"description"` // 变动描述
	}

	var req UpdateBalanceRequest
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 验证金额
	if req.Amount == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "变动金额不能为0",
		}
		c.ServeJSON()
		return
	}

	// 更新会员余额并记录
	err = models.UpdateMemberBalanceWithLog(
		id,
		req.Amount,
		4, // 4:管理员调整
		"",
		"",
		req.Description,
		permResult.Admin.Username,
		permResult.Admin.FranchiseId,
	)

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新会员余额失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回更新结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新会员余额成功",
	}
	c.ServeJSON()
}

// BatchGet 添加批量获取会员信息的接口
func (c *MemberController) BatchGet() {
	perResult := CheckControllerPermission(c.Ctx)
	if perResult == nil {
		c.Data["json"] = ErrorResponse("没有权限")
		c.ServeJSON()
		return
	}
	// 获取请求中的ID数组
	var params struct {
		IDs []uint `json:"ids"`
	}

	err := json.Unmarshal(c.Ctx.Input.RequestBody, &params)
	if err != nil {
		c.Data["json"] = ErrorResponse(err.Error())
		c.ServeJSON()
		return
	}

	if len(params.IDs) == 0 {
		c.Data["json"] = SuccessResponse([]interface{}{})
		c.ServeJSON()
		return
	}

	// 获取批量会员信息
	var members []*models.Member
	for _, id := range params.IDs {
		member, err := models.GetMemberById(int64(id), perResult.Admin.FranchiseId)
		if err == nil && member != nil {
			members = append(members, member)
		}
	}

	c.Data["json"] = SuccessResponse(members)
	c.ServeJSON()
}
